package com.example.word.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.dict.R;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.util.CommonUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 学习计划
 */
public class AddWordActivity extends AppCompatActivity {
    private Activity mActivity;
    private ActionBar mTitleBar;//标题栏
    private TextView wordEn;
    private Button btnSave;//保存
    private Spinner dictSelect;
    private String account;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_word);
        mActivity = this;
        wordEn = findViewById(R.id.wordEn);
        btnSave = findViewById(R.id.btn_save);
        dictSelect = findViewById(R.id.dictSelect);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(mActivity,"新增单词", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        initView();
    }

    private void initView() {
        account = (String) SPUtils.get(mActivity,"account","");
        List<Dict> dictList = Dict.findAll(Dict.class);
        List<String> itemsArray = new ArrayList<>();
        for (Dict dict : dictList) {
            itemsArray.add(dict.getTitle());
        }
        // 创建 ArrayAdapter 并设置下拉选项的样式
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, itemsArray);
        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 将适配器设置到 Spinner
        dictSelect.setAdapter(adapter);

        //保存
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String wordEnString;
                String dict = null;
                try {
                    wordEnString = wordEn.getText().toString();
                    dict = dictSelect.getSelectedItem().toString();
                } catch (Exception e) {
                    MessageUtils.show("请填写完整信息", mActivity);
                    return;
                }

                if ("".equals(dict) || "".equals(wordEnString)) {
                    MessageUtils.show("请填写完整信息", mActivity);
                    return;
                }
                Word exist = Word.where("word = ?", wordEnString.replace("'", "''")).findFirst(Word.class);
                if (exist == null) {
                    Word word = new Word();
                    word.setWord(wordEnString);
                    word.setDict(dict);
                    word.save();

                    // 此处只更新例句和音标，释义在学习时去有道云查询
                    HttpUtils.sendGetRequestStringResponse(CommonUtils.wordDetailUrl + word.getWord(), new HashMap<>(), responseString -> {
                        // 处理请求成功的情况
                        JSONObject jsonObject = null;
                        Word databaseWord = Word.where("word = ? and dict = ?", word.getWord().replace("'", "''"), word.getDict()).findFirst(Word.class);

                        // 1.设置音标
                        try {
                            jsonObject = new JSONObject(responseString);
                            JSONObject simpleObject = jsonObject.getJSONObject("simple").getJSONArray("word").getJSONObject(0);
                            databaseWord.setUkphone(simpleObject.getString("ukphone"));
                            databaseWord.setUsphone(simpleObject.getString("usphone"));
                        } catch (JSONException e) {
                            try {
                                JSONObject simpleObject = jsonObject.getJSONObject("simple").getJSONArray("word").getJSONObject(0);
                                databaseWord.setUkphone(simpleObject.getString("phone"));
                                databaseWord.setUsphone(simpleObject.getString("phone"));
                            } catch (JSONException jsonException) {
                                databaseWord.setUkphone(databaseWord.getWord());
                                databaseWord.setUsphone(databaseWord.getWord());
                            }
                        }

                        // 2.设置例句
                        try {
                            JSONArray jsonArray = jsonObject.getJSONObject("blng_sents_part").getJSONArray("sentence-pair");

                            String sentences = "";
                            for (int i = 0; i < jsonArray.length(); i++) {
                                try {
                                    JSONObject sentenceObject = jsonArray.getJSONObject(i);
                                    sentences += sentenceObject.getString("sentence") + "<enzh>" + sentenceObject.getString("sentence-translation") + "<split>";
                                } catch (JSONException e) { }
                            }
                            databaseWord.setSentences(sentences);
                        } catch (JSONException e) {
                            databaseWord.setSentences("该单词暂无例句");
                        }

                        databaseWord.save();
                    });

                    // 例句异步更新，单词此时已经保存了，直接提示成功
                    MessageUtils.show("保存成功！", mActivity);
                    finish();//关闭页面
                } else {
                    MessageUtils.show("该单词已存在！", mActivity);
                }
            }
        });

    }
}
